package com.alstudio.utils.android.net;

import java.util.ArrayList;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.alstudio.app.ALLocalEnv;
import com.alstudio.utils.log.ALLog;

/**
 * 本类用于封装网络事件管理。
 * 
 * @author alonso lee
 * 
 */
public class ALConnectionManager {

	private static NetworkInfo mActivieNetworkInfo;
	private static NetworkInfo mLastActiveNetworkInfo;
	private static ALConnectionType mNetworkType = ALConnectionType.TYPE_NONE;
	private static ArrayList<ALNetworkChangedListener> listeners = new ArrayList<ALNetworkChangedListener>();

	/**
	 * 更新网络连接状态
	 * 
	 * @param newNetworkInfo
	 */
	public static void updateConnectionInfo(NetworkInfo newNetworkInfo) {
		mLastActiveNetworkInfo = mActivieNetworkInfo;
		mActivieNetworkInfo = newNetworkInfo;
		if (getConnectionType() != ALConnectionType.TYPE_NONE) {
			if (mLastActiveNetworkInfo == null) {
				ALLog.e("data connection established: " + getConnectionType());
				notifyDataConnectionEstablished(getConnectionType());
			} else {
				if (getLastConnectionType() == getConnectionType()) {
					ALLog.d("there is no need to reconnect");
				} else {
					ALLog.d("网络连接类型改变当前为："+getConnectionType()+" 上一个连接类型为: "+getLastConnectionType());
					// 需要重连
					notifyDataConnectionEstablished(getConnectionType());

				}
			}

		} else {
			ALLog.e("data connection loss!");
			notifyDataConnectionLost();
			mLastActiveNetworkInfo = null;
		}
	}

//	/**
//	 * 处理手机网络变化的事件。在网络可用情况下判断是否 已经连接分发器，做登录服务器的操作。
//	 * 
//	 * @author Alonso Lee
//	 */
//	private synchronized void handleUINetworkChangeEvent(Intent intent) {
//		// 首先查看数据网络是否已不可用
//		if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,
//				false)) {
//			// 数据网络不可用了！
//			curNetworkType = "";
//			oldNetworkType = "";
//			Mylog.w(TAG, "当前无可用网络");
//			isNoNetworkConnection = true;
//			App.isNetWorkAviable = false;
//
//		} else {
//			App.isNetWorkAviable = true;
//			isNoNetworkConnection = false;
//			// 数据网络仍然有效。断开当前连接，重新登录服务器
//			NetworkInfo activeNetInfo = mConnectivityManager
//					.getActiveNetworkInfo();
//
//			if (activeNetInfo != null) {
//				Mylog.e(TAG, "当前网络连接类型: " + activeNetInfo.getTypeName());
//				curNetworkType = activeNetInfo.getTypeName();
//				if (curNetworkType.equals(oldNetworkType)) {
//					return;
//				}
//
//				oldNetworkType = curNetworkType;
//
//				if (activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
//					Mylog.e(TAG, "### 当前wifi启用了！开始获取bssid ###");
//					getCurrentBssid();
//				}
//
//				// 网络出现变化，马上开始连接服务器
//				reconnect(true, App.myAccount.getUsername(),
//						App.myAccount.getPassword(),
//						"handleUINetworkChangeEvent", false);
//
//				// 通知UI,网络可用
//				Intent i = new Intent(Events.NOTIFY_UI_NETWORK_AVAILABLE);
//				sendBroadcast(i);
//
//			}
//
//		}
//	}

	/**
	 * 检测网络是否可用
	 * 
	 * @return
	 */
	public static boolean isNetWorkConnected() {
		boolean isConnected = false;
		ConnectivityManager connMgr = (ConnectivityManager) ALLocalEnv
				.getLocalEnv().getContext()
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
		mLastActiveNetworkInfo = mActivieNetworkInfo;
		mActivieNetworkInfo = activeInfo;
		if (activeInfo != null && activeInfo.isConnected()) {
			isConnected = true;
		} else {
		}
		return isConnected;
	}

	/**
	 * 获取当前网络类型
	 * 
	 * @return
	 */
	public static ALConnectionType getConnectionType() {
		if (mActivieNetworkInfo != null) {
			if (mActivieNetworkInfo.isConnected()) {
				if (mActivieNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
					mNetworkType = ALConnectionType.TYPE_WIFI;
				} else {
					mNetworkType = ALConnectionType.TYPE_MOBILE;
				}
				return mNetworkType;
			}
		}
		mNetworkType = ALConnectionType.TYPE_NONE;
		return mNetworkType;
	}

	/**
	 * 获取字符串形式的当前网络类型
	 * 
	 * @return
	 */
	public static String getConnectionTypeString() {
		if (mActivieNetworkInfo != null) {
			if (mActivieNetworkInfo.isConnected()) {
				return mActivieNetworkInfo.getTypeName();
			}
		}
		return "";
	}

	/**
	 * 获取上一个网络状态
	 * 
	 * @return
	 */
	public static ALConnectionType getLastConnectionType() {

		if (mLastActiveNetworkInfo != null) {
			ALConnectionType lastNetworkType = ALConnectionType.TYPE_NONE;
			if (mLastActiveNetworkInfo.isConnected()) {
				if (mLastActiveNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
					lastNetworkType = ALConnectionType.TYPE_WIFI;
				} else {
					lastNetworkType = ALConnectionType.TYPE_MOBILE;
				}
				return lastNetworkType;
			}
		}
		return ALConnectionType.TYPE_NONE;
	}

	public static void AddNetworkChangedListener(
			ALNetworkChangedListener listener) {
		if (!listeners.contains(listener)) {
			listeners.add(listener);
		}
	}

	public static void removeNetworkChangedListener(
			ALNetworkChangedListener listener) {
		if (listeners.contains(listener)) {
			listeners.remove(listener);
		}
	}

	private static void notifyDataConnectionEstablished(ALConnectionType type) {
		for (ALNetworkChangedListener l : listeners) {
			l.onDataConnectionEstablished(type);
		}
	}

	private static void notifyDataConnectionLost() {
		for (ALNetworkChangedListener l : listeners) {
			l.onDataConnectionLost();
		}
	}

	public enum ALConnectionType {
		TYPE_NONE, TYPE_WIFI, TYPE_MOBILE,
	}

}
